package com.laobiao.file_netty_lib.packet.data;

import java.nio.ByteBuffer;
import java.util.Arrays;

import com.laobiao.file_netty_lib.exception.FileBaseException;
import com.laobiao.file_netty_lib.packet.BasePacket;
import com.laobiao.file_netty_lib.packet.PacketType;
import com.laobiao.file_netty_lib.util.BinaryConvertUtil;

public class BaseDataPacket extends BasePacket{

	/**
	 * 业务组编号
	 */
//	private int businessGroup;
	/**
	 * 当前包内容长度
	 */
	private int contentSize;
	/**
	 * 当前包内容
	 */
	private byte[] content;
	
	
	/**
	 * 根据数据内容构建包
	 * @param businessGroup
	 * @param content 内容，长度不能大于1015
	 */
	public BaseDataPacket(int businessGroup,byte[] content) {
		// TODO Auto-generated method stub
		if(content==null || content.length>1015) {
			throw new FileBaseException("构建数据包错误，数据内容错误，内容不能为空，且长度不能大于1015", FileBaseException.ERR_PARAM_WRONG);
		}
		setPacketType(PacketType.DATA);
		contentSize=content.length;
//		this.businessGroup=businessGroup;
		setBusinessGroup(businessGroup);
		this.content=content;
	}
	
	/**
	 * 根据数据包全结构字节数组构建数据包
	 * @param packetBytes
	 */
	public BaseDataPacket(byte[] packetBytes) {
		ByteBuffer buf=ByteBuffer.wrap(packetBytes);
		setPacketType(PacketType.instance((int)buf.get()));//包类型
		//取命令组编码
		byte[] chunk=new byte[4];
		buf.get(chunk);
		setBusinessGroup(BinaryConvertUtil.byteArrayToInt(chunk));
		//取内容长度
		chunk=new byte[4];
		buf.get(chunk);
		this.contentSize=BinaryConvertUtil.byteArrayToInt(chunk);
		//取内容
		content=new byte[this.contentSize];
		buf.get(content);
	}
	
	@Override
	public byte[] getPacketBytes() {
		ByteBuffer buf=ByteBuffer.allocate(1024);
		buf.put(BinaryConvertUtil.intToByte(getPacketType().getType()));//包类型
		buf.put(BinaryConvertUtil.intToByteArray(getBusinessGroup()));//业务组编号
		buf.put(BinaryConvertUtil.intToByteArray(contentSize));//内容长度
		buf.put(content);
		return buf.array();
	}

//	public int getCommandGroup() {
//		return businessGroup;
//	}
//
//	public void setCommandGroup(int commandGroup) {
//		this.businessGroup = commandGroup;
//	}

	public int getContentSize() {
		return contentSize;
	}

	public void setContentSize(int contentSize) {
		this.contentSize = contentSize;
	}

	public byte[] getContent() {
		return content;
	}

	public void setContent(byte[] content) {
		this.content = content;
	}

	@Override
	public String toString() {
		return "BaseDataPacket [commandGroup=" + getBusinessGroup() + ", contentSize=" + contentSize + ", content="
				+ Arrays.toString(content) + "]";
	}
}
